package com.scrx.ymg.dao.address;

import java.io.File;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.scrx.ymg.dao.base.BaseDaoImpl;
import com.scrx.ymg.entity.Address;
import com.scrx.ymg.entity.User;

@Repository("addressDao")
@Transactional
public class AddressDaoImpl extends BaseDaoImpl implements IAddressDao {


	public String save(Address add) {

        try {
            getCurrentSession().save(add);
          return "true";
        } catch (RuntimeException re) {
          return "false";
        }
    }


	public List<Address> getAddress(String userID) {
		 Query query=getCurrentSession().createQuery("from Address where userId=:userId and superId!=-1");
		 query.setParameter("userId", Integer.parseInt(userID));
		 if (query.list().size()>0) {
			return (List<Address>)query.list();
		}
		return null;
	}
	public Address getAddress(String userID,String superID) {
		 Query query=getCurrentSession().createQuery("from Address where userId=? and superId=?");
		 query.setParameter(0, Integer.parseInt(userID));
		 query.setParameter(1, Integer.parseInt(superID));
		 List<Address> list=query.list();
		 Address add=null;
		 if(list!=null&&list.size()>0){
			 add=list.get(0);
		 }
		return add;
	}

	public Address getAddressByID(String addID) {
		 Query query=getCurrentSession().createQuery("from Address where id=?");
		 query.setParameter(0, Integer.parseInt(addID));
		
		return  (Address)query.uniqueResult();
	}



	public String deleteAddress(Address add) {
        try {
        	getCurrentSession().delete(add);
          return "true";
        } catch (RuntimeException re) {
          return "false";
        }
	}



	public List<Address> getAllAddress(String userID) {
		 Query query=getCurrentSession().createQuery("from Address where userId=:userId");
		 query.setParameter("userId", Integer.parseInt(userID));
		if (query.list().size()>0) {
			return (List<Address>)query.list();
		}
		return null;
	}



	public String saveAddressAndUpdateUser(Address add, User user) {
		try {
			getCurrentSession().save(add);
			getCurrentSession().update(user);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
		}
	}

}
